package db

import (
	"encoding/json"
	"functime"
	"time"

	"fmt"

	"github.com/garyburd/redigo/redis"
)

var globalConn redis.Conn

func Redis_InitData() {
	conn, err := redis.DialTimeout("tcp", ":6379", 0, 1*time.Second, 1*time.Second)
	if err != nil {
		fmt.Println("redis conn fail:", err)
	}
	globalConn = conn

	for i := 0; i < PlayerNum; i++ {
		uid := 1000 + i + 1

		cnt, _ := redis.Int(conn.Do("SCARD", uid))
		if cnt > 0 {
			continue
		}

		user := NewUser(uid)
		body, err := json.Marshal(user)
		if err != nil {
			panic(err.Error())
		}

		_, err = conn.Do("SADD", user.UID, string(body))
		if err != nil {
			panic(err.Error())
		}
	}
}

func Redis_RunStress() {
	fc := functime.NewFuncTime()
	defer fc.End("Redis_RunStress")

	//	wg := sync.WaitGroup{}

	for n := 0; n < PlayerNum; n++ {
		//		wg.Add(1)
		func() {
			for i := 1; i <= FriendNum; i++ {
				uid := 1000 + i
				jsonUser, err := redis.Strings(globalConn.Do("SMEMBERS", uid))
				if err != nil {
					panic(err.Error())
				}

				var user User
				json.Unmarshal([]byte(jsonUser[0]), &user)

				//				users = append(users, &user)
				//				fmt.Println("redis get user:", user)
			}
			//			wg.Done()
		}()
	}

	//	wg.Wait()
}
